import React, { Component }  from 'react';
class SetStatePage extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            counter:0
         }
    }
    componentDidMount(){
        // this.changeValue(1) 
        document.getElementById('test').addEventListener('click',this.setCounter)
    }
    changeValue=v=>{
        //setStage在合成事件和生命周期中是异步的，这里说的异步其实是批量更新，达到优化性能目的
        // this.setState({
        //     counter:this.state.counter + v
        // },()=>{
        //     console.log('counter',this.state.counter)
        // })
        // console.log('counter',this.state.counter)
        //批量更新
        this.setState((state)=>{
          return {
              counter:state.counter + v
          }
        })
    }
    setCounter=()=>{
       //setState在setTimeout和原生事件中是同步
    //    setTimeout(() => {
    //     this.changeValue(1) 
    //    }, 0);
       this.changeValue(1) 
       this.changeValue(2)
    }
    render() { 
        return ( 
            <div>
                <h3>SetStagePage</h3>
                <button onClick={this.setCounter}>{this.state.counter}</button>
                <button id="test">原生事件*{this.state.counter}</button>
            </div>
         );
    }
}
 
export default SetStatePage;